/**
 * cart 购物车状态管理模块
 */
const cartModule = {
  namespaced: true, // 启动命名空间
  state: {
    cart: [] // 购物车数组
  },
  getters: {
    /**
     * 计算出是否所有商品都选中
     * @param {*} state
     * @returns
     */
    allChecked (state) {
      return state.cart.every(prod => prod.checked)
    },
    /**
     * 合计金额
     * @param {*} state
     */
    totalMoney (state) {
      return state.cart.reduce((sum, prod) => {
        if (prod.checked) {
          sum += prod.price * prod.amount
        }
        return sum
      }, 0)
    },
    /**
     * 合计数量
     */
    totalAmount (state) {
      return state.cart.reduce((sum, prod) => {
        if (prod.checked) {
          sum += prod.amount
        }
        return sum
      }, 0)
    }
  },
  mutations: { // 同步更新状态数据的mutation方法
    // 加入购物车
    addToCart (state, payload) {
      // 查询购物车中是否有当前选购的商品
      const product = state.cart.find(prod => prod.id === payload.currentProduct.id)
      if (product) {
        product.amount += payload.currentProduct.amount
      } else {
        state.cart.push({
          ...payload.currentProduct,
          checked: false // 单选框是否勾选，默认否
        })
      }
    },
    // 删除购物车商品
    removeFromCart (state, payload) {
      state.cart = state.cart.filter(prod => prod.id !== payload.id)
    },
    // 修改数量
    modifyAmount (state, payload) {
      // 找到购物车中的商品
      const product = state.cart.find(prod => prod.id === payload.id)
      product.amount = payload.amount
    },
    // 修改购物车的选中状态
    modifyChecked (state, payload) {
      const product = state.cart.find(prod => prod.id === payload.id)
      // 修改选中状态 取反
      product.checked = !product.checked
    },
    /**
       * 修改全选/取消全选
       */
    modifyAllChecked (state, payload) {
      state.cart = state.cart.map(prod => {
        prod.checked = payload.allChecked
        return prod
      })
    }
  }
}

export default cartModule
